import {reactive, toRaw} from "vue";
import feedback from "@/utils/feedback";


// 分页钩子函数
interface Options {
    page?: number
    size?: number
    fetchFun: (any: any) => Promise<any>
    params?: Record<any, any>
    firstLoading?: boolean
}


/**
 * 使用分页
 *
 * @param options
 */
export function usePagerManager(options: Options) {

    // 定义
    const {page = 1, size = 10, fetchFun, params = {}, firstLoading = false} = options
    const paramsInit: Record<any, any> = Object.assign({}, toRaw(params))
    // 分页数据
    const pagerData = reactive({
        page,
        size,
        loading: firstLoading,
        count: 0,
        lists: [] as any[]
    })

    /**
     *   请求分页接口
     */
    function getPageLists() {
        pagerData.loading = true

        fetchFun({
            pageRequest: {
                pageNo: pagerData.page,
                pageSize: pagerData.size,
            },
            ...params
        })
            .then((res: any) => {

                pagerData.count = res?.count
                pagerData.lists = res?.lists ?? res
                return Promise.resolve(res)

            })
            .catch((err: any) => {
                feedback.notifyError("获取分页列表错误")
            })
            .finally(() => {
                pagerData.loading = false
            })
    }

    /**
     *   重置为第一页
     */
    function resetOnePage() {
        pagerData.page = 1
        getPageLists()
    }


    /**
     * 重置参数
     */
    function resetParams() {

        Object.keys(paramsInit).forEach((item) => {
            params[item] = paramsInit[item]
        })
        getPageLists()
    }


    return {pagerData, getPageLists, resetParams, resetOnePage}
}

